package com.jiuxian.scheduling.util;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

/**
 * Created by wangjingqing on 2017/12/22.
 */
public class ZKLock {

    Logger logger = LoggerFactory.getLogger(ZKLock.class);

    private String path;

    private String mark;
    static{
        ZKClientUtil.createNode(ZKClientUtil.ROOT_LOCK);
    }
    public ZKLock(String path){
        this.path = path;
        ZKClientUtil.createNode(ZKClientUtil.ROOT_LOCK+"/"+path);
    }
    /**
     * 获取锁<br>
     */
    public boolean tryLock(){
        try {
            mark = ZKClientUtil.zk.createEphemeralSequential(ZKClientUtil.ROOT_LOCK + "/"+path+"/"+path, new Date());
            List<String> paths = ZKClientUtil.zk.getChildren(ZKClientUtil.ROOT_LOCK+"/"+path);
            paths.sort((d1,d2)->{
                if(d1.compareTo(d2) < 0){
                    return -1;
                }else if(d1.compareTo(d2) > 0){
                    return 1;
                }
                return 0;
            });
            if(mark.equals(ZKClientUtil.ROOT_LOCK+"/"+path+"/"+paths.get(0))){
                return true;
            }
            return false;
        } catch (RuntimeException e) {
            logger.error("获取锁异常,",e);
        }
        return false;
    }

    /**
     * 释放锁<br>0
     */
    public boolean unLock(){
        try {
            Thread.sleep(RandomUtils.nextInt(100,300));
            ZKClientUtil.zk.delete(mark);
            return true;
        } catch (Exception e) {
            logger.error("释放锁失败:,",e);
        }
        return false;
    }
}
